/**
 * Created by zhanglihe on 15/11/19.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog',
    'fineuploader',
    'calendar'
], function ($, common, ready, Collection, template, Model, dialog, fineuploader, calendar) {
    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.fetch();
            this.event();
        },

        fetch: function () {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'jd_orders',
                condition: {limit: 10, offset: 0},
                model: {
                    url: _global.url.api + 'order/{id}',
                    event: {
                        '.item-shipping:click': 'order_shipping',
                        '.item-follow:click': 'order_follow',
                        '.item-refund:click': 'order_refund',
                        '.item-log:click': 'order_log'
                    },
                    order_follow: function (e) {
                        e.preventDefault();
                        var _this = this;
                        dialog({
                            title: '跟进订单:' + _this.data.sn + ',收货人:' + _this.data.shipping_name,
                            content: template('order_follow-tpl'),
                            width: 400,
                            modal: true,
                            ok: function () {
                                var data = {};
                                data.action = 'follow';
                                data.note = $('textarea[name="note"]').val();
                                if (new Model({
                                        url: _global.url.api + 'order/' + _this.data.id,
                                        data: data
                                    }).put()) {
                                }
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    order_refund: function (e) {
                        e.preventDefault();
                        var __this = this;
                        dialog({
                            title: '订单:' + __this.data.sn + ',收货人:' + __this.data.shipping_name,
                            content: '确定要申请退款？<br>申请后，需要商家同意操作',
                            modal: true,
                            ok: function () {
                                var data = {};
                                data.order_id = __this.data.id;
                                if (new Model({
                                        url: _global.url.api + 'order_apply_refund',
                                        data: data
                                    }).put()) {
                                    //重新加载
                                    _this.collection.reload();
                                }
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    order_shipping: function (e) {
                        e.preventDefault();
                        var __this = this;
                        dialog({
                            title: "订单：" + __this.data.sn,
                            content: '此操作仅在系统无法发货时操作<br />正常情况不需要手工操作<br />操作完成后请查看日志列表',
                            modal: true,
                            width: 500,
                            ok: function () {
                                $.ajax({
                                    url: 'http://api.sixishop.com/get_jd_order_info?key='+__this.data.apikey+'&id=' + __this.data.id,
                                    type: 'get',
                                    async: false,
                                    success: function (res) {
                                        _this.collection.reload();
                                    }
                                });
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    order_log: function (e) {
                        e.preventDefault();
                        var _this = this;
                        $.ajax({
                            url: _global.url.api + 'order_log',
                            data: {id: _this.data.id},
                            type: 'get',
                            async: false,
                            success: function (res) {
                                if (res.code == 0) {
                                    var dialogObj = dialog({
                                        title: '订单日志:' + _this.data.sn + ',收货人:' + _this.data.shipping_name,
                                        width: 600,
                                        height: 500,
                                        modal: true,
                                        content: template('order_log-tpl', {data: res.data}),
                                        cancel: function () {
                                            $('body').css('overflow', 'auto');
                                        }
                                    });
                                    dialogObj._$('content').css('overflow', 'auto');
                                    dialogObj.show();
                                    $('body').css('overflow', 'hidden');
                                } else {
                                    alert(res.msg);
                                }
                            }
                        });
                    }
                },
                callback: function () {
                    loaded();
                }
            });
            this.collection.fetch();
        },

        event: function () {
            var _this = this;
            //日期
            $('.form_datetime').calendar();
            /**
             * 搜索事件
             */
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                click_search();
            });
            var click_search = function (fun) {
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.condition.start_time = $('input[name="start_time"]').val();
                _this.collection.condition.end_time = $('input[name="end_time"]').val();
                _this.collection.callback = function () {
                    if (fun && fun == 'toExcel') {
                        toExcel();
                        _this.collection.callback = function () {
                        }
                    }
                }
                _this.collection.reload();
            }

            /**
             * 按状态查询
             */
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                $('input[name="keyword"]').val('');
                $('input[name="start_time"]').val('');
                $('input[name="end_time"]').val('');
                _this.collection.condition.keyword = '';
                _this.collection.condition.start_time = '';
                _this.collection.condition.end_time = '';
                _this.collection.condition.status = $(e.target).attr('rel');
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });

            //to excel
            var href;
            var toExcelWindow;
            $(".btn-excel").on("click", function (e) {
                e.preventDefault();
                href = $(this).attr('href');
                toExcelWindow = dialog({
                    content: '请稍等 ,正在导出...',
                    width: 200,
                    modal: true
                }).show();
                click_search('toExcel');
            });
            var toExcel = function () {
                toExcelWindow.close();
                console.log(_this.collection.result._count);
                var limit = 1000;
                var params = '';
                var data = _this.collection.condition;
                var total = _this.collection.result._count;

                if (total < 1) {
                    alert('没有需要导出的订单');
                    return false;
                }

                for (var i in data) {
                    if (i == 'limit' || i == 'offset') continue;
                    params = params + '&' + i + '=' + encodeURIComponent(data[i]);
                }
                href = (href.indexOf('?') === -1) ? href + '?' : href;
                href = href + params + '&limit=' + limit + '&offset=';

                if (total > limit) {
                    var showData = {};
                    showData.pages = Math.ceil(total / limit);
                    showData.total = total;
                    showData.limit = limit;
                    showData.href = href;
                    dialog({
                        title: '导出订单列表Excel文件',
                        content: template('to-excel-tpl', showData),
                        width: 600,
                        heigth: 500,
                        modal: true,
                        ok: function () {
                        },
                        cancel: function () {
                        }
                    }).show();
                } else {
                    window.location.href = href;
                }
            }

            //import excel
            $('#btn_import').on('click', function (e) {
                import_shipped(e);
            });

            var import_shipped = function (e) {
                e.preventDefault();
                var uploadWindow = dialog({
                    title: '从Excel文件导入订单发货单信息',
                    content: template('import-shipped-tpl', {}),
                    width: 500,
                    modal: true
                }).show();
                //上传相关
                $("#J_Upload").fineUploader({
                    request: {
                        endpoint: window._global.url.api + 'OrderShippingFile?access_token=' + window._global.access_token,
                        inputName: 'filedata',
                        params: {
                            access_token: window._global.access_token
                        }
                    },
                    multiple: false,
                    deleteFile: {
                        enabled: false
                    },
                    text: {
                        uploadButton: '选择文件'
                    }
                }).on('complete', function (event, id, fileName, response) {
                    $(".not-result").show();
                    if (response.code == 0) {
                        uploadWindow.content('121');
                        uploadWindow.close();
                        shipping_confirm(response);
                    } else {
                        var msg = response.msg ? response.msg : '系统异常';
                        $('#result').html(msg);
                    }
                }).on('upload', function (event, id, filename) {
                    $('#result').html('正在上传文件,请不要关闭浏览器');
                }).on('progress', function (event, id, filename, loaded, total) {
                    $(".not-result").hide();
                    var dd = parseInt((loaded / total) * 100);
                    $('#result').html(dd == 100 ? '上传完成,正在处理,请稍等...' : '正在上传文件,请不要关闭浏览器,已经上传:' + dd + '%');
                });
            };

            var opt_data_arr = [];
            var shipping_confirm = function (data) {
                var _data = data.data;
                var confirmOptIdArr = [];
                for (var i = 0; i < _data.length; i++) {
                    var tmpId = _data[i].id;
                    confirmOptIdArr.push(tmpId);
                    opt_data_arr[tmpId] = _data[i];
                }
                batch_shipping(true, confirmOptIdArr);
                /*
                 console.log(opt_data_arr);
                 var tmpWindows = dialog({
                 title: '订单发货确认',
                 content: template('data-shipping', data),
                 width: 980,
                 height: 500,
                 modal: true,
                 ok: function () {
                 batch_shipping();
                 },
                 cancel: function () {
                 }
                 }).show();
                 tmpWindows._$('content').css('overflow','auto');
                 tmpWindows.content('121');
                 tmpWindows.close();
                 */
            }


            //批量发货
            var isOpt = true;
            var batch_shipping = function (is_confirm, confirmOptIdArr) {
                is_confirm = is_confirm ? is_confirm : false;
                var optTotal = is_confirm ? confirmOptIdArr.length : $('.shipping-data:checked').size();
                if (optTotal < 1) {
                    alert('请选择要处理的数据！');
                    return false;
                }

                //增加执行队列
                var optIdArr = [];
                if (is_confirm) {
                    optIdArr = confirmOptIdArr;
                } else {
                    $('.shipping-data:checked').each(function () {
                        var tmpId = $(this).val();
                        optIdArr.push(tmpId);

                        opt_data_arr[tmpId].shipping_no = $("input[name='shipping_no_" + tmpId + "']").val();
                        opt_data_arr[tmpId].shipping_note = $("input[name='shipping_note_" + tmpId + "']").val();
                    });
                }

                isOpt = true;

                var _height = 180 + optTotal * 20;
                if (_height > 500)  _height = 500;

                var dialogObj = dialog({
                    id: 'batch_agreetmpId',
                    title: '批量发货：',
                    content: '发货启动中...............',
                    width: 980,
                    height: _height,
                    modal: true,
                    cancelValue: '关闭|中止',
                    cancel: function () {
                        isOpt = false;
                    }
                });
                dialogObj._$('content').css('overflow', 'auto');
                dialogObj.show();

                var OptI = 0;
                var oldOptI = -1;
                var errorArr = [];

                //处理
                var int = self.setInterval(function () {
                    if (!isOpt) {
                        alert('已经中止操作');
                        dialogObj.close();
                        int = window.clearInterval(int);
                        _this.collection.reload();//操作结束
                        return false;
                    }
                    if (OptI >= optTotal) {
                        int = window.clearInterval(int);
                        _this.collection.reload();//操作结束

                        dialogObj.title('全部处理完毕');
                        if (errorArr.length > 0) {
                            var ret = {};
                            ret.total = optTotal;
                            ret.okNum = optTotal - errorArr.length;
                            ret.errorNum = errorArr.length;
                            dialogObj.content(template('data-shipping-return', {'ret': ret, 'data': errorArr}));
                        }
                        return true;
                    }
                    if (oldOptI > -1 && oldOptI == OptI) {
                        //中途错误，将继续处理
                        return false;
                    }
                    oldOptI = OptI;
                    var tmpId = optIdArr[OptI];
                    var item = opt_data_arr[tmpId];
                    var tmpTitle = (OptI + 1) + '::订单号：' + item.sn + '，  收货人手机：' + item.shipping_mobile + '，  快递：' + item.express_name + '，  单号：' + item.shipping_no;
                    var _content = '需要处理：' + optTotal + ',已经处理：' + (OptI + 1) + '<br /><br />';

                    dialogObj.title(tmpTitle);
                    dialogObj.content(_content);

                    var data = {};
                    data.action = 'deliver';
                    data.shipping_no = item.shipping_no;
                    data.shipping_note = item.shipping_note;
                    data.express_id = item.express_id;
                    var tmpModel = new Model({
                        url: _global.url.api + 'order/' + tmpId,
                        data: data
                    });
                    tmpModel.error = function (result) {
                        tmpModel.msg = result;
                    }
                    if (tmpModel.put()) {
                        dialogObj.content(_content + '当前操作:处理成功');
                    } else {
                        var tmpData = item;
                        tmpData.msg = tmpModel.msg;
                        errorArr.push(tmpData);

                        dialogObj.content(_content + '当前操作:处理失败(' + tmpData.msg + ')');
                    }
                    OptI++;
                }, 500);
            }

        }
    };

    new index();

});